import { isString } from '@web-utils/core'

let keepAliveCache = null
let keys = null

function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

class CacheManager {
  attach(children) {
    if (children) {
      for (let i = children.length - 1; i >= 0; i--) {
        const cache = children[i].$vnode?.parent?.componentInstance?.cache
        if (cache) {
          keys = children[i].$vnode?.parent?.componentInstance?.keys
          keepAliveCache = cache
          break
        }
      }
    }
  }

  remove(key) {
    if (!keepAliveCache) {
      return
    }
    const cache = keepAliveCache[key]
    if (cache && cache.componentInstance) {
      cache.componentInstance.$destroy()
      remove(keys, key)
      keepAliveCache[key] = null
    }
  }

  get(key) {
    if (!keepAliveCache) {
      return null
    }
    const cache = keepAliveCache[key]
    if (cache && cache.componentInstance) {
      return keepAliveCache[key]
    }
    return null
  }

  getCache() {
    return keepAliveCache
  }

  destroy() {
    keepAliveCache = null
  }
}

export const cacheManager = new CacheManager()

export function getTestMenus() {
  return [
    {
      icon: 'menu-icon el-icon-lx-home',
      id: '0-1',
      path: '/',
      title: '首页'
    },
    {
      icon: 'icon-form',
      id: '1',
      title: '廉政建设',
      children: [
        {
          icon: 'icon-form',
          id: '1-1',
          path: '',
          title: '1-1',
          children: [
            {
              icon: 'icon-form',
              id: '1-1-1',
              path: '/',
              title: '1-1-1'
            },
            {
              icon: 'icon-form',
              id: '1-1-2',
              path: '/',
              title: '1-1-2'
            },
            {
              icon: 'icon-form',
              id: '1-1-3',
              path: '/',
              title: '1-1-3'
            },
            {
              icon: 'icon-form',
              id: '1-1-4',
              path: '/',
              title: '1-1-4'
            }
          ]
        }
      ]
    }
  ]
}

export function getIndex(item) {
  if (item.path && isString(item.path)) {
    const index = item.path.indexOf('?')
    return index > -1 ? item.path.substring(0, index) : item.path
  }
  return item.id
}

export function getKey(item) {
  return item.id
}
